package com.wangbo.rabbit.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.util.Map;

@UtilityClass
public class JacksonUtil {
    private ObjectMapper objectMapper;

    /**
     * json -> bean
     */
    @SneakyThrows
    public <T> T toBean(String json, Class<T> clz) {
        if (objectMapper == null)
            objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, clz);
    }

    /**
     * json -> List
     */
    @SneakyThrows
    public <T> T toList(String json, TypeReference<T> clz) {
        if (objectMapper == null)
            objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, clz);
    }

    /**
     * bean -> json String
     */
    @SneakyThrows
    public String toJson(Object obj) {
        if (objectMapper == null)
            objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(obj);
    }

    /**
     * json -> Map
     **/
    @SneakyThrows
    public Map toMap(String json) {
        if (objectMapper == null)
            objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, Map.class);
    }

}
